import router from '@/router'
import store from '@/store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const WHITE_LIST = ['/404', '/login']

router.beforeEach(async(to, from, next) => {
  NProgress.start()

  const token = store.getters.token

  if (token) {
    if (to.path === '/login') {
      next('/')
      Message.info('您已登陆，请不要调皮')
      NProgress.done()
    } else {
      const userInfo = store.getters.userInfo
      if (!userInfo.username) {
        await store.dispatch('user/getUserInfo')
      }
      next()
    }
  } else {
    if (WHITE_LIST.indexOf(to.path) !== -1) {
      next()
    } else {
      Message.info('登录已过期')
      next(`/login?_redirect=${to.path}`)
    }
  }
})

router.afterEach((to, from) => {
  NProgress.done()
})
